<?php

class ECategory extends DataObject {

    static $db = array(
        'Title' => 'Varchar(255)',
        'UrlSegment' => 'Varchar(255)',
        'SortOrder' => 'Int'
    );
    static $has_one = array(
//        'ProductHolder' => 'ProductHolder'
    );

    static $has_many = array(
        'EpalProductHolders' => 'EpalProductHolder'
    );

    static $belongs_many_many = array(
        'EProducts' => 'EProduct'
    );

    static $singular_name = 'Product Category';
    public static $default_sort = 'SortOrder';

    function getCMSFields() {
        $fields = parent::getCMSFields();

        $fields->addFieldsToTab('Root.Main', array(
            new TextField('Title', 'Title'),
            new TextField('UrlSegment', 'Url Segment'),
            new HiddenField('SortOrder')
        ));
        return $fields;
    }

    function onBeforeWrite() {
        parent::onBeforeWrite();

        if($this->Title == null || $this->Title == ''){
            $this->Title  = 'category-'.$this->ID;
        }

        if($this->UrlSegment == null || $this->UrlSegment == ''){
            $this->UrlSegment = $this->checkUniqueUrlSegment(SiteTree::create()->generateURLSegment($this->Title));
        }else{
            $this->UrlSegment = $this->checkUniqueUrlSegment(SiteTree::create()->generateURLSegment($this->UrlSegment));
        }

    }

    static $summary_fields = array(
        'Title' => 'Title'
    );

    function checkUniqueUrlSegment($url_segment){

        $categories = ECategory::get()->filter(array('UrlSegment' => $url_segment));

        $num = time();

        if($categories->Count() > 0){
            if($categories->Count() == 1){
                $category = $categories->first();
                if( $category->ID == $this->ID ){
                    return $url_segment;
                }else{
                    return $url_segment . '-' . $num;
                }
            }else{
                return $url_segment . '-' . $num;
            }
        }
        return $url_segment;

    }

    function CategoryLink(){
        return EpalShop_Controller::$URLCategory.'/'.$this->UrlSegment;
    }

}